package com.duojuhe.websocket.socket;

import com.duojuhe.cache.LoginUserTokenCache;
import com.duojuhe.common.bean.UserTokenInfoVo;
import com.duojuhe.common.constant.SystemConstants;
import com.duojuhe.common.enums.SystemEnum;
import com.duojuhe.common.utils.iputil.IPUtils;
import com.duojuhe.common.utils.token.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * socket握手拦截器
 *
 */
@Service
@Slf4j
public class SocketInterceptor implements HandshakeInterceptor {
    @Resource
    private LoginUserTokenCache loginUserTokenCache;
    /**
     * socket握手拦截
     *
     * @param request
     * @param response
     * @param wsHandler
     * @param attributes
     * @return boolean
     * @throws Exception
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        if(!SystemConstants.SYSTEM_INIT_SUCCESS){
            return false;
        }
        HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
        //获取token
        String token = TokenUtils.getTokenByRequest(servletRequest);
        if (StringUtils.isBlank(token)){
            return false;
        }
        //检查是否登录了
        UserTokenInfoVo userTokenInfoVo = loginUserTokenCache.getUserTokenInfoVoCacheByToken(token);
        if(userTokenInfoVo==null){
            return false;
        }
        //终端类型
        String clientType = SocketUtil.getClientTypeByRequest(servletRequest);
        //当前会话token
        attributes.put(TokenUtils.TOKEN_HEADER, token);
        //请求终端id
        attributes.put(SocketUtil.USER_ID, userTokenInfoVo.getUserId());
        //当前链接客户端类型
        attributes.put(SocketUtil.CLIENT_TYPE, StringUtils.isBlank(clientType)? SystemEnum.LOGIN_RESOURCE.SYSTEM_ADMIN.getKey():clientType);
        //获取客户端ip
        String clientIp = IPUtils.getClientIP(servletRequest);
        attributes.put(SocketUtil.CLIENT_IP, clientIp);
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
    }
}
